<template>
  <Dialog title="评价计划详情" v-model="dialogVisible" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="计划名称" prop="planName">
            <el-input v-model="formData.planName" placeholder="请输入计划名称" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划编号" prop="planCode">
            <el-input v-model="formData.planCode" placeholder="请输入计划编号" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="职业工种" prop="professionId">
            <el-input v-model="formData.professionName" placeholder="职业工种" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="评价等级" prop="level">
            <el-input v-model="formData.levelName" placeholder="评价等级" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="计划状态" prop="planStatus">
            <el-input v-model="formData.planStatusText" placeholder="计划状态" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="适用等级" prop="applicableLevels">
            <el-input v-model="formData.applicableLevels" placeholder="适用等级" readonly />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="考评员" prop="kpyrName">
            <el-input v-model="formData.kpyrName" placeholder="考评员" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="评价方式" prop="evaluationMethod">
            <el-input v-model="formData.evaluationMethodText" placeholder="评价方式" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="评价模板" prop="templateId">
            <el-input v-model="formData.templateName" placeholder="评价模板" readonly />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="最大人数" prop="maxPeoplePerPlan">
            <el-input v-model="formData.maxPeoplePerPlan" placeholder="最大人数" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!-- 占位列 -->
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="报名开始日期" prop="registrationStartDate">
            <el-input v-model="formData.registrationStartDate" placeholder="报名开始日期" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报名结束日期" prop="registrationEndDate">
            <el-input v-model="formData.registrationEndDate" placeholder="报名结束日期" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="评价开始日期" prop="evaluationStartDate">
            <el-input v-model="formData.evaluationStartDate" placeholder="评价开始日期" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="评价结束日期" prop="evaluationEndDate">
            <el-input v-model="formData.evaluationEndDate" placeholder="评价结束日期" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="计划描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          placeholder="请输入计划描述"
          :rows="3"
          readonly
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入备注"
          :rows="2"
          readonly
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { getTemplate } from '@/api/eval/template'

defineOptions({ name: 'PlanDetail' })

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: null as number | null,
  planName: '',
  planCode: '',
  batchName: '',
  professionId: 0,
  professionName: '',
  professionCode: '',
  applicableLevels: '',
  kpyrName: '',
  evaluationMethod: '',
  evaluationMethodText: '',
  templateId: undefined,
  templateName: '',
  levelName: '',
  description: '',
  remark: '',
  registrationStartDate: '',
  registrationEndDate: '',
  evaluationStartDate: '',
  evaluationEndDate: '',
  maxPeoplePerPlan: 0,
  contactPerson: '',
  contactPhone: '',
  contactEmail: '',
  planDescription: '',
  planStatus: 0,
  planStatusText: '',
  targetAudience: 'all',
  targetDepartments: '',
  targetPositions: ''
})
const formRules = reactive({
  planName: [{ required: true, message: '计划名称不能为空', trigger: 'blur' }],
  planCode: [{ required: true, message: '计划编号不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 获取评价方式文本 */
const getEvaluationMethodText = (method: string) => {
  const textMap = {
    'assessment': '考核评价',
    'competency': '岗位能力评价',
    'combined': '考评结合',
    'competition': '竞赛认定'
  }
  return textMap[method] || method
}

/** 获取状态文本 */
const getStatusText = (status: number) => {
  const textMap = {
    0: '草稿',
    1: '已提交',
    2: '已审批',
    3: '已发布',
    4: '进行中',
    5: '已完成',
    6: '已取消'
  }
  return textMap[status] || '未知'
}

/** 格式化日期数组为字符串 */
const formatDateArray = (dateArray: number[]) => {
  if (!Array.isArray(dateArray) || dateArray.length < 3) {
    return ''
  }
  const [year, month, day] = dateArray
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
}

/** 模拟获取计划数据 */
const getPlanData = async (id: number) => {
  // 这里应该调用真实的API，暂时返回模拟数据
  return {
    id: id,
    planName: 'test',
    planCode: 'PLAN-20250812-102614',
    batchName: 'test',
    professionId: 1,
    professionName: '电工',
    professionCode: '6-18-01-01',
    applicableLevels: '一级',
    evaluationMethod: 'combined',
    registrationStartDate: [2025, 8, 12],
    registrationEndDate: [2025, 8, 13],
    evaluationStartDate: [2025, 8, 14],
    evaluationEndDate: [2025, 8, 15],
    maxPeoplePerPlan: 50,
    contactPerson: '小林',
    contactPhone: '131',
    contactEmail: '131@qq.com',
    planDescription: 'test',
    planStatus: 0,
    targetAudience: 'all',
    targetDepartments: '',
    targetPositions: ''
  }
}

/** 打开弹窗 */
const open = async (id?: number) => {
  dialogVisible.value = true
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      // 从父组件传递的数据中获取（实际项目中应该调用API）
      // 这里我们从列表数据中获取对应的记录
      const planData = await getPlanData(id)

      if (planData) {
        formData.value.id = planData.id
        formData.value.planName = planData.planName || ''
        formData.value.planCode = planData.planCode || ''
        formData.value.batchName = planData.batchName || ''
        formData.value.professionId = planData.professionId || 0
        formData.value.professionName = planData.professionName || ''
        formData.value.professionCode = planData.professionCode || ''
        formData.value.applicableLevels = planData.applicableLevels || ''
        formData.value.kpyrName = (planData as any).kpyrName || ''
        formData.value.evaluationMethod = planData.evaluationMethod || ''
        formData.value.evaluationMethodText = getEvaluationMethodText(planData.evaluationMethod || '')
        formData.value.templateId = (planData as any).templateId || undefined
        formData.value.levelName = planData.applicableLevels || ''
        formData.value.description = planData.planDescription || ''
        formData.value.remark = (planData as any).remark || ''

        // 获取模板名称
        if ((planData as any).templateId) {
          try {
            const templateData = await getTemplate((planData as any).templateId)
            formData.value.templateName = templateData.templateName || '未知模板'
          } catch (error) {
            console.error('获取模板信息失败:', error)
            formData.value.templateName = '获取失败'
          }
        } else {
          formData.value.templateName = '未选择'
        }

        // 处理日期格式 - 如果是数组格式则转换为字符串
        formData.value.registrationStartDate = Array.isArray(planData.registrationStartDate)
          ? formatDateArray(planData.registrationStartDate)
          : planData.registrationStartDate || ''
        formData.value.registrationEndDate = Array.isArray(planData.registrationEndDate)
          ? formatDateArray(planData.registrationEndDate)
          : planData.registrationEndDate || ''
        formData.value.evaluationStartDate = Array.isArray(planData.evaluationStartDate)
          ? formatDateArray(planData.evaluationStartDate)
          : planData.evaluationStartDate || ''
        formData.value.evaluationEndDate = Array.isArray(planData.evaluationEndDate)
          ? formatDateArray(planData.evaluationEndDate)
          : planData.evaluationEndDate || ''

        formData.value.maxPeoplePerPlan = planData.maxPeoplePerPlan || 0
        formData.value.contactPerson = planData.contactPerson || ''
        formData.value.contactPhone = planData.contactPhone || ''
        formData.value.contactEmail = planData.contactEmail || ''
        formData.value.planDescription = planData.planDescription || ''
        formData.value.planStatus = planData.planStatus || 0
        formData.value.planStatusText = getStatusText(planData.planStatus || 0)
        formData.value.targetAudience = planData.targetAudience || 'all'
        formData.value.targetDepartments = planData.targetDepartments || ''
        formData.value.targetPositions = planData.targetPositions || ''
      }
    } catch (error) {
      console.error('获取计划数据失败:', error)
      ElMessage.error('获取计划数据失败')
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: null,
    planName: '',
    planCode: '',
    batchName: '',
    professionId: 0,
    professionName: '',
    professionCode: '',
    applicableLevels: '',
    kpyrName: '',
    evaluationMethod: '',
    evaluationMethodText: '',
    templateId: undefined,
    templateName: '',
    levelName: '',
    description: '',
    remark: '',
    registrationStartDate: '',
    registrationEndDate: '',
    evaluationStartDate: '',
    evaluationEndDate: '',
    maxPeoplePerPlan: 0,
    contactPerson: '',
    contactPhone: '',
    contactEmail: '',
    planDescription: '',
    planStatus: 0,
    planStatusText: '',
    targetAudience: 'all',
    targetDepartments: '',
    targetPositions: ''
  }
  formRef.value?.resetFields()
}
</script>